package com.huobao.shangjia_version.activitys;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.xutils.common.util.LogUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huobao.yunying.activitys.Act_Tuikuan_detail;
import com.huobao.yunying.adapters.StoreDingdanManagerAdapter;
import com.huobao.yunying.adapters.TuihuoAdapter;
import com.huobao.yunying.entity.Guige;
import com.huobao.yunying.entity.Ordership;
import com.huobao.yunying.entity.StoreSingDanData;
import com.huobao.yunying.entity.Storeordergoods;
import com.huobao.yunying.entity.TuihuanHuoList;
import com.huobao.yunying.fragments.BaseFragment;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.utils.DialogUtils;
import com.huobao.yunying.utils.DialogUtils.onDialogDiamissListener;
import com.huobao.zhangying.R;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Store_DingdanManagerFragment extends BaseFragment implements OnScrollListener, OnCheckedChangeListener,OnItemClickListener {

	private StoreDingdanManagerAdapter adapter;
	private TuihuoAdapter tuihuo_adapter;
	private boolean isLoading = true;
	private ListView listview;
	private String type;
	private int m_CurrentPage = 1;
	private TextView tv_foot_msg;

//	private CheckBox box;
//	private TextView btn_quxiao;

	/**
	 * [0已取消 11待付款 10已提交 20待发货 30已发货 40已完成]为空则显示全部订单
	 * 
	 * @param type
	 */
//	public Store_DingdanManagerFragment(String type) {
//		this.type = type;
//	}
	public static Store_DingdanManagerFragment getInstant(String type){
		Store_DingdanManagerFragment instance = new Store_DingdanManagerFragment();
		Bundle args = new Bundle();
		args.putString("type",type);
		instance.setArguments(args);
		return instance;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		EventBus.getDefault().register(this);
		View view = inflater.inflate(R.layout.test, null);
		this.type = getArguments().getString("type");
		listview = (ListView) view.findViewById(R.id.listview);
		listview.setOnScrollListener(this);
		View FootView = inflater.inflate(R.layout.item_footview, null);
//		View headview = inflater.inflate(R.layout.item_progect_headview, null);
//		box = (CheckBox) headview.findViewById(R.id.checkbox);
//		box.setOnCheckedChangeListener(this);
//		btn_quxiao = (TextView) headview.findViewById(R.id.btn_1);
		tv_foot_msg = (TextView) FootView.findViewById(R.id.tv_message);
		listview.addFooterView(FootView);
//		listview.addHeaderView(headview);
		listview.setOnItemClickListener(this);
		adapter = new StoreDingdanManagerAdapter(getActivity(),type);
		tuihuo_adapter = new TuihuoAdapter(getActivity());
		if (type == null) {
			listview.setAdapter(tuihuo_adapter);
			getTuihuo(true);
		} else {
			listview.setAdapter(adapter);
			getDate(true);
		}
//		check();
//		btn_quxiao.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				StringBuffer sb = new StringBuffer();
//				StringBuffer sb1 = new StringBuffer();
//				List<StoreSingDanData> datas = new ArrayList<StoreSingDanData>();
//				for (StoreSingDanData data : adapter.getList()) {
//					if(!data.isChecked)continue;
//					sb1.append("订单号：" + data.order_sn);
//					sb1.append("\n");
//					sb.append(data.order_id);
//					sb.append(",");
//					datas.add(data);
//				}
//				if (sb.toString().equals(""))
//					return;
//				showCancelDialog(sb1.toString(), sb.toString().substring(0, sb.toString().length() - 1), datas);
//			}
//		});
		return view;
	}

	@Subscriber(tag = "cancaleOrder")
	public void cancaleOrder(StoreSingDanData data) {
		showCancelDialog("订单号：" + data.order_sn, data.order_id, null);
	}
	@Subscriber(tag = "refreshDing")
	public void refreshDing(String s){
		m_CurrentPage = 1;
		getDate(true);
	}

	private boolean isSkip = false;
	@Subscriber(tag = "onitemclick")
	public void onitemclick(int position){
		LogUtil.e("onitemclick===================");
		if(isSkip)return;
		isSkip = true;
		Intent intent;
		if (type == null) {
			intent = new Intent(getActivity(), Act_Tuikuan_detail.class);
			intent.putExtra("id", tuihuo_adapter.getItem(position).order_id);
			getActivity().startActivity(intent);
			return;
		}
		intent = new Intent(getActivity(), Act_Store_dingdan_detail.class);
		intent.putExtra("order_id", adapter.getItem(position).order_id);
		getActivity().startActivity(intent);
		isSkip = false;
	}
	private void showCancelDialog(String msg, final String data, final List<StoreSingDanData> datas) {
		DialogUtils.showCancelOrderDialog(getActivity(), msg, new onDialogDiamissListener() {

			@Override
			public void onDialogDismiss(String...strings) {
				Map<String, String> map = HttpUtil.getParams("app", "sellerorder", "act", "cancel_order", "order_id",
						data);
				Http.getInstant().sendRequest(getActivity(), map, new HttpListener() {

					@Override
					public void onHttpSuccess(String result) {
						Toast.makeText(getActivity(), "取消订单成功", Toast.LENGTH_SHORT).show();
						getDate(true);
					}

					@Override
					public void onHttpError(String error) {

					}
				});
			}
		});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}

//	private void check() {
//		int status = type == null || type.equals("null") || type.equals("") ? -1 : Integer.parseInt(type);
//		btn_quxiao.setText("取消订单");
//		btn_quxiao.setTextColor(Color.parseColor("#FF3732"));
//		switch (status) {
//		// [0已取消 11待付款 10已提交 20待发货 30已发货 40已完成]
//		case 0:
//			box.setEnabled(false);
//			btn_quxiao.setEnabled(false);
//			break;
//		case 11:
//			box.setEnabled(true);
//			btn_quxiao.setEnabled(true);
//			break;
//		case 10:
//			// tv_status.setText("状态：已提交 ");
//			// tv_diaozhengfeiyong.setVisibility(View.);
//			// tv_shoudaohuokuan.setVisibility(View.);
//			// tv_wuliu.setVisibility(View.);
//			// tv_quxiao_dingdan.setVisibility(View.);
//			// tv_danhao.setVisibility(View.);
//			// checkbox.setEnabled(enabled);
//			break;
//		case 20:
//			box.setEnabled(true);
//			btn_quxiao.setEnabled(true);
//			break;
//		case 30:
//			box.setEnabled(true);
//			btn_quxiao.setEnabled(true);
//			break;
//		case 40:
//			box.setEnabled(false);
//			btn_quxiao.setEnabled(false);
//			break;
//		}
//	}

	private void getTuihuo(boolean isShowDialog) {
		isLoading = true;
		Map<String, String> map = HttpUtil.getParams("app", "sellerorder", "act", "refundlist", "page",
				m_CurrentPage + "");
		Http.getInstant().sendRequest(getActivity(), isShowDialog, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				List<TuihuanHuoList> list = JSON.parseArray(jsonObject.getString("retval"), TuihuanHuoList.class);
				if (list == null || list.size() == 0) {
					tv_foot_msg.setText("加载完成");
					isLoading = true;
					return;
				}
				tuihuo_adapter.addAll(list);
				isLoading = false;
			}

			@Override
			public void onHttpError(String error) {
			}
		});
	}

	private void getDate(boolean isShowDialog) {
		isLoading = true;
		Map<String, String> map = HttpUtil.getParams("app", "sellerorder", "status", type, "page", m_CurrentPage + "");
		Http.getInstant().sendRequest(getActivity(), isShowDialog, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				JSONArray array = jsonObject.getJSONArray("retval");
				List<StoreSingDanData> list = new ArrayList<StoreSingDanData>();
				for (int i = 0; i < array.size(); i++) {
					JSONObject object = array.getJSONObject(i);
					StoreSingDanData data = JSON.parseObject(object.toString(), StoreSingDanData.class);
					List<Storeordergoods> goods = JSON.parseArray(object.getString("ordergoods"),
							Storeordergoods.class);
					Ordership ordership = JSON.parseObject(object.getString("ordership"),Ordership.class);
					data.ordergoods = goods;
					data.ordership = ordership;
					list.add(data);
				}
				if (list == null || list.size() == 0) {
					tv_foot_msg.setText("加载完成");
					isLoading = true;
					return;
				}
				adapter.addAll(list);
				isLoading = false;
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (isLoading)
			return;
		if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
			m_CurrentPage++;
			if (type == null)
				getTuihuo(false);
			else
				getDate(false);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		for (StoreSingDanData data : adapter.getList()) {
			data.isChecked = isChecked;
		}
		adapter.notifyDataSetChanged();
	}

}
